// 动画是定格的图片
// 需要保证在不同帧率下动画效果相同
import React, { useEffect, useRef } from 'react';
import * as THREE from 'three';

export default function index() {
  const mounRef = useRef(null);
  useEffect(() => {
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );
    camera.position.set(1, 1, 10);
    camera.lookAt(0, 0, 0); // 明确看向原点
    scene.add(camera);

    const axesHelper = new THREE.AxesHelper(5);
    scene.add(axesHelper);

    const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
    const boxMeterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
    const boxMesh = new THREE.Mesh(boxGeometry, boxMeterial);
    scene.add(boxMesh);
    const boxMesh2 = new THREE.Mesh(boxGeometry, boxMeterial);
    boxMesh2.position.set(0, 3, 1);
    boxMesh2.rotation.x = Math.PI * 0.2;
    boxMesh2.rotation.y = Math.PI * 0.4;
    scene.add(boxMesh2);

    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    mounRef.current.appendChild(renderer.domElement); // 将渲染器的DOM元素添加到React组件
    renderer.render(scene, camera);

    // animation
    // 确保不同帧率下动画效果相同，使用时间差
    let time = Date.now();
    // 2、使用 THREE.Clock 计算时间差
    const clock = new THREE.Clock();

    const animation = () => {
      const animaTime = Date.now();
      const detal = animaTime - time;
      time = animaTime;
      boxMesh.position.x += 0.001 * detal;
      if (boxMesh.position.x > 10) {
        boxMesh.position.x = 0;
      }
      // 2、clock获取上一帧到当前帧的时间差（秒）
      const deltaTime = clock.getDelta();
      boxMesh2.rotation.y += 0.1 * Math.PI * deltaTime;
      renderer.render(scene, camera);
      window.requestAnimationFrame(animation); // 会在下一帧调用此函数
    };
    animation();
  }, []);
  return (
    <div
      ref={mounRef}
      style={{ width: '100%', height: '100%' }}
    />
  );
}
